package com.edu.boot301demo.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

public class MyYamlHttpMessageConverter extends AbstractHttpMessageConverter<Object> {
    private final ObjectMapper objectMapper; // 把对象转成Yaml

    @Override
    protected boolean supports(Class<?> clazz) {
        // 只要是Object类型，都支持，不支持基本数据类型
        return true;
    }

    @Override // 读取数据 对应注解：@RequestBody
    protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        return null;
    }

    @Override // 写入数据 对应注解：@ResponseBody
    protected void writeInternal(Object returnValue, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        try (OutputStream body = outputMessage.getBody()) {
            body.write(objectMapper.writeValueAsBytes(returnValue));
        }


    }

    public MyYamlHttpMessageConverter() {
        // 告诉父类，这个转换器支持application/yaml
        super(new MediaType("application", "yaml", StandardCharsets.UTF_8));
        YAMLFactory factory = new YAMLFactory().disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER);
        this.objectMapper = new ObjectMapper(factory);
    }
}
